package com.treasure.mall.zbqmallmanager.boot;

import com.treasure.mall.biz.bo.BaseConfig;
import com.treasure.mall.biz.bo.config.BasicsConfig;
import com.treasure.mall.biz.bo.config.WithdrawConfig;
import com.treasure.mall.biz.entity.auth.SystemManager;
import com.treasure.mall.biz.entity.auth.SystemMenu;
import com.treasure.mall.biz.entity.auth.SystemRole;
import com.treasure.mall.biz.entity.product.SpecialAreaPO;
import com.treasure.mall.biz.entity.wechat.WechatConfigPO;
import com.treasure.mall.biz.repository.system.SystemManagerRepository;
import com.treasure.mall.biz.repository.system.SystemMenuRepository;
import com.treasure.mall.biz.service.core.BaseConfigService;
import com.treasure.mall.biz.service.core.auction.AuctionSessionService;
import com.treasure.mall.biz.service.core.auth.SystemService;
import com.treasure.mall.biz.service.core.order.DealOrderService;
import com.treasure.mall.biz.service.core.product.SpecialAreaService;
import com.treasure.mall.biz.service.core.statistics.DealAmountStatisticsService;
import com.treasure.mall.biz.service.core.statistics.OrderStatisticsService;
import com.treasure.mall.biz.service.core.wechat.WechatConfigService;
import com.treasure.mall.biz.service.core.withdraw.WithdrawService;
import com.treasure.mall.zbq.common.ienum.RoleType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.Year;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author allan
 * @date 2018-08-06
 */
@Component
@Slf4j
public class ApplicationBoot {

    @Autowired
    private SystemService systemService;
    @Autowired
    private SystemManagerRepository systemManagerRepository;

    @Autowired
    private SystemMenuRepository systemMenuRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private SpecialAreaService specialAreaService;

    @Resource
    private BaseConfigService baseConfigService;

    private SystemManager manager;


    @Autowired
    private WechatConfigService wechatConfigService;
    @Autowired
    private WithdrawService withdrawService;


    @PostConstruct
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public void init() {
        initSystemConfig();
        initWechatConfig();
        initSystemManager();
        initSystemMenu();
        initArea();
//        initScheduled();
    }

    public void initArea() {
        List<SpecialAreaPO> specialAreaPOS = specialAreaService.findAreaAll();
        if (specialAreaPOS.size() == 0) {
            specialAreaService.addArea("1001", "好物推荐", "好物推荐");
            specialAreaService.addArea("1002", "一元捡漏", "一元捡漏");
            specialAreaService.addArea("1003", "今日甄选", "今日甄选");
            specialAreaService.addArea("1004", "精品特卖", "精品特卖");
        }
    }

    /**
     * 初始化系统管理员
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public void initSystemManager() {
        if (systemManagerRepository.count() == 0) {
            LocalDateTime dateTime = LocalDateTime.now();
            SystemRole role = new SystemRole();
            role.setEnable(true);
            role.setRoleName("超级管理员");
            role.setRoleType(RoleType.Default.getCode());
            role.setCreateTime(dateTime);
            role.setAuthority("");
            role.setUserId(-1);
            role = systemService.saveRole(role);
            manager = new SystemManager();
            manager.setRole(role);
            manager.setCreateTime(dateTime);
            manager.setLoginName("admin");
            manager.setEnable(true);
            manager.setParentUserId(0);
            manager.setLoginPwd(passwordEncoder.encode("root123"));
            manager.setLastLoginTime(dateTime);
            systemService.saveManager(manager);
        }
    }

    /**
     * 初始化系统菜单
     */
    public void initSystemMenu() {
        List<SystemMenu> menuList = systemMenuRepository.findAll();
        if (menuList == null || menuList.size() == 0) {
            boolean isFunction = false;
            SystemMenu menu = saveMenu(0, "系统配置", 50, "none", "cogs", isFunction, null);
            Integer pid = menu.getItemCode();
            //功能权限
            Map<String, String> functionMap = new HashMap<>();
            functionMap.put("/sys/ajax/save", "添加和编辑");
            functionMap.put("/sys/ajax/list", "列表");
            functionMap.put("/sys/ajax/details", "详情");
            functionMap.put("/sys/ajax/activate", "设置状态");
            functionMap.put("/sys/ajax/delete", "删除");
            saveMenu(pid, "菜单管理", 2, "/sys/menus", "bars", isFunction, functionMap);

            functionMap.clear();
            functionMap.put("/sys/ajax/rolelist", "列表");
            functionMap.put("/sys/ajax/editrole", "添加和编辑");
            functionMap.put("/sys/ajax/deleterole", "删除");
            functionMap.put("/sys/ajax/setpower", "设置权限");
            functionMap.put("/sys/ajax/setenable", "设置状态");
            functionMap.put("/sys/ajax/list", "权限列表");
            saveMenu(pid, "角色管理", 3, "/sys/roles", "user", isFunction, functionMap);

            functionMap.clear();
            functionMap.put("/sys/ajax/editmanager", "添加和编辑");
            functionMap.put("/sys/ajax/managerlist", "列表");
            functionMap.put("/sys/ajax/setuserenable", "设置状态");
            saveMenu(pid, "账户管理", 4, "/sys/manager", "users", isFunction, functionMap);


            functionMap.clear();
            functionMap.put("/config/ajax/save", "编辑");
            saveMenu(pid, "全局配置", 0, "/config/getConfig", "list", isFunction, functionMap);


            functionMap.clear();
            saveMenu(pid, "广告列表", 1, "/banner/list", "list", isFunction, functionMap);
            functionMap.clear();
            saveMenu(pid, "添加广告", 1, "/banner/edit", "edit", false, isFunction, functionMap);


            menu = saveMenu(0, "产品管理", 49, "none", "file-text-o", isFunction, null);
            pid = menu.getItemCode();
            functionMap.clear();
//            functionMap.put("/goods/ajax/goodslist", "列表");
//            functionMap.put("/goods/ajax/deletegoods", "删除");
//            functionMap.put("/goods/ajax/updategoodsstatus", "上架和下架");
            saveMenu(pid, "店铺商品列表", 1, "/product/normalList", "list", isFunction, functionMap);


            saveMenu(pid, "类目管理", 3, "/category/list", "pencil-square-o", true, isFunction, functionMap);
            saveMenu(pid, "专区管理", 3, "/specialArea/list", "list", isFunction, functionMap);

            menu = saveMenu(0, "用户管理", 48, "none", "users", isFunction, null);
            pid = menu.getItemCode();
            functionMap.clear();

            saveMenu(pid, "粉丝列表", 3, "/user/list?type=0", "list", isFunction, functionMap);

            functionMap.clear();
            saveMenu(pid, "会员列表", 3, "/user/list?type=1", "list", isFunction, functionMap);
            functionMap.clear();
            menu = saveMenu(pid, "提现管理", 3, "none", "list", isFunction, functionMap);
            pid = menu.getItemCode();
            functionMap.clear();
            saveMenu(pid, "提现列表", 1, "/withdraw/list", "list", isFunction, functionMap);
            saveMenu(pid, "提现配置", 1, "/withdraw/config", "list", isFunction, functionMap);
            functionMap.clear();

            menu = saveMenu(0, "订单管理", 47, "none", "list", isFunction, null);
            pid = menu.getItemCode();
            functionMap.clear();
            saveMenu(pid, "销售订单", 1, "/order/list", "list", isFunction, functionMap);
            saveMenu(pid, "业务订单", 1, "/order/biz/list", "list", isFunction, functionMap);
            saveMenu(pid, "售后申请", 1, "/order/afterSale/list", "list", isFunction, functionMap);
            saveMenu(pid, "发货单", 1, "/order/deliver/list", "list", isFunction, functionMap);

            menu = saveMenu(0, "商户管理", 48, "none", "folder", isFunction, null);
            pid = menu.getItemCode();
            functionMap.clear();
            saveMenu(pid, "商户列表", 1, "/merchant/list?dataType=1", "list", isFunction, functionMap);
            saveMenu(pid, "审核列表", 2, "/merchant/list?dataType=0", "list", isFunction, functionMap);


            //桌面
            saveMenu(0, "桌面", 0, "/desktop", "desktop", isFunction, null);
        }
    }

    /**
     * 保存功能菜单
     *
     * @param pid
     * @param title
     * @param url
     */
    private void saveFunctionMenu(Integer pid, String title, String url) {
        saveMenu(pid, title, 1, url, "", true, null);
    }

    /**
     * 保存菜单
     *
     * @param pid
     * @param title
     * @param sort
     * @param url
     * @param iconCls
     * @return
     */
    private SystemMenu saveMenu(Integer pid, String title, int sort, String url, String iconCls, boolean isFunction, Map<String, String> functionMap) {
        return saveMenu(pid, title, sort, url, iconCls, true, isFunction, functionMap);
    }

    private SystemMenu saveMenu(Integer pid, String title, int sort, String url, String iconCls, boolean isEnable, boolean isFunction, Map<String, String> functionMap) {
        SystemMenu menu = new SystemMenu();
        menu.setCreateTime(LocalDateTime.now());
        menu.setItemParentCode(pid);
        menu.setItemEnable(isEnable);
        menu.setItemName(title);
        menu.setItemSort(sort);
        menu.setItemPath(url);
        menu.setItemIconCls(iconCls);
        menu.setItemFunction(isFunction);
        menu.setItemChildCount(Long.valueOf(0));
        systemService.save(menu);
        Integer itemCode = menu.getItemCode();
        if (functionMap != null) {
            functionMap.forEach((key, value) -> saveFunctionMenu(itemCode, value, key));
        }
        return menu;
    }


    public void initSystemConfig() {

        if (!baseConfigService.exist()) {
            BaseConfig baseConfig = new BaseConfig();
            baseConfig.setBasicsConfig(new BasicsConfig());
            baseConfig.setWithdrawConfig(new WithdrawConfig());
            baseConfigService.save(baseConfig);
        }

    }


    public void initWechatConfig() {
        if (!wechatConfigService.exist()) {
            wechatConfigService.save(new WechatConfigPO("wx91cff11b228f1a99", "f0623570b65f9c5cc731140ff91840f3", "数农小程序"));
            wechatConfigService.save(new WechatConfigPO("wxc2764391ade782f2", "76a171861eb028d4c0f76da91427b41c", "数农|文玩线上交易平台"));
        }
    }

    @Autowired
    private DealOrderService dealOrderService;
    @Autowired
    private AuctionSessionService auctionSessionService;

    /**
     * 初始化一些定时任务
     */
    public void initScheduled() {
        //初始化支付超时订单任务
        dealOrderService.initScheduled();
        //初始化拍卖任务
        auctionSessionService.initSchedule();
    }

    /**
     * 修复提现老数据，执行一遍后，删除
     */
    public void repairWithdrawOldData() {
        withdrawService.repairOldData();
    }

    @Autowired
    private DealAmountStatisticsService dealAmountStatisticsService;
    @Autowired
    private OrderStatisticsService orderStatisticsService;

    /**
     * 执行一次
     */
    public void initStatistics() {
        Year year = Year.now();
        //7月份
        for (int i = 1; i <= Month.JULY.maxLength(); i++) {
            LocalDate date = LocalDate.of(year.getValue(), Month.JULY, i);
            dealAmountStatisticsService.statistics(date);
            orderStatisticsService.statistics(date);
        }
        //8月份
        for (int i = 1; i <= Month.AUGUST.maxLength(); i++) {
            LocalDate date = LocalDate.of(year.getValue(), Month.AUGUST, i);
            dealAmountStatisticsService.statistics(date);
            orderStatisticsService.statistics(date);
        }
        //9月份
        for (int i = 1; i <= Month.SEPTEMBER.maxLength(); i++) {
            LocalDate date = LocalDate.of(year.getValue(), Month.SEPTEMBER, i);
            dealAmountStatisticsService.statistics(date);
            orderStatisticsService.statistics(date);
        }
        //10月，统计到11号
        for (int i = 1; i <= 22; i++) {
            LocalDate date = LocalDate.of(year.getValue(), Month.OCTOBER, i);
            dealAmountStatisticsService.statistics(date);
            orderStatisticsService.statistics(date);
        }

//        LocalDate date = Jsr310Utils.Date.of("2020-10-04");
//        dealAmountStatisticsService.statistics(date);
//
//        date = Jsr310Utils.Date.of("2020-10-05");
//        dealAmountStatisticsService.statistics(date);
//
//        date = Jsr310Utils.Date.of("2020-10-06");
//        dealAmountStatisticsService.statistics(date);
//
//        date = Jsr310Utils.Date.of("2020-10-07");
//        dealAmountStatisticsService.statistics(date);
//
//        date = Jsr310Utils.Date.of("2020-10-08");
//        dealAmountStatisticsService.statistics(date);
//
//        date = Jsr310Utils.Date.of("2020-10-09");
//        dealAmountStatisticsService.statistics(date);
//
//        date = Jsr310Utils.Date.of("2020-10-10");
//        dealAmountStatisticsService.statistics(date);
    }
}
